<template>
  <div class="container EditArticle">
    <div class="auto">
      <a-card hoverable>
        <span slot="title" v-if="!$route.query.articleId"><a-icon style="float: left; margin-top: 4px; margin-right: 8px; cursor: pointer" type="rollback" @click="goBack"/>新增文章</span>
        <span slot="title" v-else><a-icon style="float: left; margin-top: 4px; margin-right: 8px; cursor: pointer" type="rollback" @click="goBack"/>编辑文章</span>
        <a-spin :spinning="confirmLoading">
          <a-form :form="form">
            <a-row class="rowStyle">
              <a-col>
                <a-button type="primary" @click="submit" style="float: right;">发布</a-button>
              </a-col>
            </a-row>
            <a-row  class="rowStyle">
              <span class="modelTitle">基础信息</span>
            </a-row>
            <a-row>
              <a-col span="7">
                <a-form-item label="文章标题" >
                    <a-input
                      placeholder="请输入文章标题"
                      v-decorator="['title', validatorRules.title ]"/>
                </a-form-item>
              </a-col>
              <a-col span="7" offset="1">
                <a-form-item label="所属栏目" >
                      <a-tree-select
                        v-decorator="['columnId', validatorRules.columnId ]"
                        style="width: 100%"
                        :replaceFields="replaceFields"
                        :tree-data="departTree"
                        placeholder="请选择所属栏目!"
                      />
                </a-form-item>
              </a-col>
              <a-col span="7" offset="1">
                <a-form-item label="设置文章附件下载权限（多选）" >
                    <a-checkbox-group placeholder="设置文章附件下载权限（多选）" v-decorator="['downloadpermission', validatorRules.downloadpermission ]" :options="options"></a-checkbox-group>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col span="7">
                <!--删除文章副标题-->
                <a-form-item label="自定义文章顺序" >
                  <a-input-number
                    style="width: 100%;"
                    placeholder="自定义文章顺序"
                    v-decorator="['order', {} ]"/>
                </a-form-item>
              </a-col>
              <a-col span="7" offset="1">
                <a-form-item label="设置发布状态" >
                    <a-radio-group :options="plainOptions" placeholder="设置发布状态" v-decorator="['type', validatorRules.type ]" />
                </a-form-item>
              </a-col>
              <a-col span="7" offset="1">
                <a-form-item label="设置文章权限（多选）" >
                    <a-checkbox-group placeholder="设置文章权限（多选）" v-decorator="['viewpermission', validatorRules.viewpermission ]" :options="options"></a-checkbox-group>
                </a-form-item>
              </a-col>
            </a-row>



            <a-row>
              <a-col span="15">
                <a-form-item label="描述">
                  <a-textarea
                    :maxLength="maxLength"
                    placeholder="请输入对该文章的简短描述，以便用户查看文章简略，字数上限300！"
                    v-decorator="['remark', validatorRules.remark ]" :autoSize ="{ minRows: 6, maxRows: 12 }"/>
                </a-form-item>
              </a-col>
              <a-col span="7" offset="1">
                <!--取消缩略图校验-->
                <a-form-item label="文章缩略图">
                  <a-upload
                    accept="image/*"
                    v-if="isRender"
                    name="file"
                    :headers="headers"
                    :data="fileData"
                    :defaultFileList="fileList"
                    :action="uploadUrl"
                    list-type="picture-card"
                    :remove="beforeRemove"
                    @preview="handlePreview"
                    @change="UploadhandleChange"
                    v-decorator="['lightPic',  {} ]"
                  >
                    <div v-if="fileList.length < 1">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">
                        上传
                      </div>
                    </div>
                    <!-- <div v-else>
                      <img :src="model.titleImgUrl" alt="">
                    </div> -->
                  </a-upload>
                </a-form-item>
                <a-modal title="文章缩略图" :visible="imgPreviewVisible" @cancel="imgHandleCancel">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                  <template slot="footer">
                    <a-button key="back" @click="imgHandleCancel">关闭</a-button>
                  </template>
                </a-modal>
              </a-col>
            </a-row>
            <a-row  style="margin-bottom: 50px;">
              <a-col span="23">
                <a-form-item
                  label="文章内容"
                  style="height: 300px">
                  <j-editor v-decorator="['content',validatorRules.content]" triggerChange :max_height="300"></j-editor>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="rowStyle">
              <a-col span="7">
                <a-form-item label="附件上传">
                  <a-upload
                    name="file"
                    :multiple="true"
                    :headers="headers"
                    :data="fileData"
                    :defaultFileList="fileList2"
                    :action="uploadUrl"
                    :remove="beforeRemove2"
                    @change="UploadhandleChange2"
                    v-decorator="['uploadPath', {}]"
                    style="display: inline">
                    <a-button>
                      <a-icon type="upload" />
                      选择导入文件
                    </a-button>
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <div>
                <span style="marginRight: 8px;">标签：</span>
                <span v-for="tag in tags" style="margin: 0px 10px 6px 0px; display: inline-block;" :key="tag.id">
                  <a-checkable-tag
                    :key="tag.id"
                    :checked="checkedTag(tag)"
                    @change="checked => handleChange(tag, checked)"
                    >
                    {{ tag.name }}
                  </a-checkable-tag>
                  <a-popconfirm title="确定删除吗?" @confirm="() => deleteTagAction(tag)">
                    <a style="font-size: 10px;">
                      <a-icon type="close" />
                    </a>
                  </a-popconfirm>
                </span>
                <a-input
                  v-if="inputVisible"
                  ref="input"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  :value="inputValue"
                  @change="handleInputChange"
                  @blur="handleInputConfirm"
                />
                <a-tag v-if="!inputVisible" style="background: #fff; borderStyle: dashed;" @click="showInput">
                  <a-icon type="plus" /> 新增标签
                </a-tag>
                <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                </a> -->
              </div>
            </a-row>
          </a-form>
        </a-spin>
      </a-card>
    </div>
  </div>
</template>

<script>
import {Modal} from 'ant-design-vue'
import JEditor from '@/moduleCompontent/JEditor'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from  "@/store/mutation-types"
import pick from 'lodash.pick'
import '../../../public/css/style.css';
import { postAction,getAction } from '@/api/manage'
import BASE_URL from '../../../config'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name: 'EditArticle',
  components: {
    JEditor
  },
  beforeRouteEnter (to, from, next) {
    window.scrollTo(0, 0);
    if(Vue.ls.get(USER_INFO) && Vue.ls.get(USER_INFO).username && Vue.ls.get(USER_INFO).role == '1') {
      next()
    } else {
      next(false)
    }
  },
  // beforeRouteLeave (to, from, next) {
  //   this.$confirm({
  //     title: '警告',
  //     content: '文章未保存，确定要退出吗?',
  //     okText: '退出',
  //     okType: 'danger',
  //     cancelText: '取消',
  //     onOk() {
  //       next()
  //     },
  //     onCancel() {
  //       next(false)
  //     },
  //   });
  // },
  data () {
    return {
      isRender: false,
      uploadUrl: BASE_URL + '/article/upload',
      confirmLoading: false,
      replaceFields: {
        value: 'id',
        title: 'name',
        key: 'id',
        children: 'children'
      },
      departTree: [],
      selectedTags: [],
      toggleSearchStatus: false,
      inputVisible: false,
      tags: [],
      inputValue: '',
      fileList2: [],
      fileList: [],
      imgPreviewVisible: false,
      previewImage: '',
      uploadAddress: '',
      // 上传头部token
      headers: {
        'token': Vue.ls.get(ACCESS_TOKEN)
      },
      // 上传附带参数
      fileData: {
        createBy: Vue.ls.get(USER_INFO).username || '游客',
      },
      maxLength: 300,
      plainOptions: [
        {
          label: '草稿',
          value: '1'
        },
        {
          label: '发布',
          value: '2'
        }
      ],
      options: [
        {
          label: '会员',
          value: '1'
        },
        {
          label: '游客',
          value: '2'
        },
        {
          label: '公开',
          value: '3'
        },
      ],
      model: {},
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      validatorRules: {
        title: {rules: [{required: true, message: '请输入文章标题!' }]},
        columnId: {rules: [{required: true, message: '请选择所属栏目!'}]},
        downloadpermission: {rules: [{required: true, message: '请选择文章附件下载权限!'}]},
        subtitle: {rules: [{required: true, message: '请输入文章副标题!' }]},
        type: {rules: [{required: true, message: '请设置文章状态!' }]},
        viewpermission: {rules: [{required: true, message: '请选择文章权限!'}]},
        remark: {rules: [{required: true, message: '请输入对该文章的简短描述，以便用户查看文章简略!'}]},
        //取消缩略图校验
        // lightPic: {
        //   // getValueFromEvent: this.normFile
        //   // rules: [{required: true, message: '请选择上传文章缩略图!'}]
        // },
        content: {rules: [{required: true, message: '请输入文章内容!'}]},
        uploadPath: {
          getValueFromEvent: this.normFile,
          rules: [{required: true, message: '请选择上传附件!'}]
        },
      }
    };
  },
  created() {
    setTimeout(() => {
    this.$nextTick(() => {

      this.getTagList()
      this.getArticleList()
      if(this.$route.query.articleId) {

        let self = this
        let url = '/article/info/' + this.$route.query.articleId
        getAction(url, {}).then(res => {
          if(res.code == 0) {
            self.isRender = true
            self.model = Object.assign({}, res.result)
            self.fileList = [
              {
                uid: '1',
                name: '头像',
                url: self.model.titleImgUrl,
                status: 'done'
              }
            ]
            for(let x in res.result.articleAttachments) {
              self.fileList2.push(
                {
                  uid: res.result.articleAttachments[x].id,
                  name: res.result.articleAttachments[x].filename,
                  status: 'done',
                  url: res.result.articleAttachments[x].attachment
                }
              )
            }
            self.model.lightPic = self.fileList
            self.model.uploadPath = self.fileList2
            self.model.type = self.model.type + ''
            for(let y in self.model.articleLabels) {
              self.selectedTags.push(self.model.articleLabels[y])
            }
            self.model.downloadpermission = self.permissionData(self.model.downloadpermission)
            self.model.viewpermission = self.permissionData(self.model.viewpermission)

            self.form.setFieldsValue(pick(self.model, 'title','columnId', 'downloadpermission', 'subtitle', 'type', 'order', 'viewpermission', 'remark', 'content', 'lightPic', 'uploadPath'))
          } else {
            self.$message.error(res.msg)
          }
        })
      } else {
        this.isRender = true
        this.model.columnId = this.$route.query.columnId
        this.form.setFieldsValue(pick(this.model, 'title','columnId', 'downloadpermission', 'subtitle', 'type', 'order', 'viewpermission', 'remark', 'content','lightPic', 'uploadPath'))
      }
    });

    });
  },
  methods: {
    permissionData(permission) {
      let b1 = permission.slice(0,1)
      let b2 = permission.slice(1,2)
      let b3 = permission.slice(2,3)
      let arr = []
      if(b1 == '1') {
        arr.push('1')
      }
      if(b2 == '1') {
        arr.push('2')
      }
      if(b3 == '1') {
        arr.push('3')
      }
      return arr
    },
    permissionSubmit(permission) {
      let x1,x2,x3
      if(permission.indexOf('1') > -1) {
        x1 = '1'
      } else {
        x1 = '0'
      }
      if(permission.indexOf('2') > -1) {
        x2 = '1'
      } else {
        x2 = '0'
      }
      if(permission.indexOf('3') > -1) {
        x3 = '1'
      } else {
        x3 = '0'
      }
      return x1+x2+x3
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    beforeRemove(file) {
      let self = this
      let url
      if (file.response) {
        url = file.response.result.fileurl
      } else {
        url = file.url
      }
      let index
      for(let x in this.fileList) {
        if(this.fileList[x].url == url) {
          index = x
        }
      }
      return new Promise((resolve, reject) => {
        this.$confirm({
          title: '确认要移除此图片?',
          onOk() {
            self.fileList.splice(index,1)
            self.form.setFieldsValue({
              'lightPic': undefined
            })
            resolve()
          },
          onCancel() {
            resolve(false)
          }
        })
      })
    },
    beforeRemove2(file) {
      let self = this
      let url
      if (file.response) {
        url = file.response.result.fileurl
      } else {
        url = file.url
      }
      let index
      for(let x in this.fileList2) {
        if(this.fileList2[x].url == url) {
          index = x
        }
      }
      return new Promise((resolve, reject) => {
        this.$confirm({
          title: '确认要移除此图片?',
          onOk() {
            self.fileList2.splice(index,1)
            if(self.fileList2.length == 0) {
              self.form.setFieldsValue({
                'uploadPath': undefined
              })
            }
            resolve()
          },
          onCancel() {
            resolve(false)
          }
        })
      })
    },
    UploadhandleChange(info) {
      if (info.file.status === 'done') {
        if(info.file.response.code != 0) {
          if (info.file.response.code == 401){
            if(info.file.response.msg.includes("invalid token")) {
              Modal.error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  Vue.ls.remove(USER_INFO)
                  window.location.href="/"
                }
              })
            } else {
              this.$message.error(`${info.file.name} ${info.file.response.msg}.`)
            }
          }
        } else {
          this.fileList.push({
            uid: this.fileList.length + 1,
            name: info.file.response.result.filename,
            status: 'done',
            url: info.file.response.result.fileurl,
          })
          this.$message.success('上传成功!')
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        } else {
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USER_INFO)
              window.location.href="/"
              // window.location.reload()
            }
          })
        }
      }
    },
    UploadhandleChange2(info) {
      if (info.file.status === 'done') {
        if(info.file.response.code != 0) {
          if (info.file.response.code == 401){
            if(info.file.response.msg.includes("invalid token")) {
              Modal.error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  Vue.ls.remove(USER_INFO)
                  window.location.href="/"
                }
              })
            } else {
              this.$message.error(`${info.file.name} ${info.file.response.msg}.`)
            }
          }
        } else {
          this.fileList2.push({
            uid: this.fileList2.length,
            name: info.file.response.result.filename,
            status: 'done',
            url: info.file.response.result.fileurl,
          })
          this.$message.success('上传成功!')
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        } else {
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USER_INFO)
              window.location.href="/"
              // window.location.reload()
            }
          })
        }
      }
    },
    getArticleList() {
      let self = this
      getAction('/column/listall', {parentId: 0}).then(res => {
        if(res.code == 0) {
          self.departTree = [...res.result]
        } else {
          self.$message.error(res.msg)
        }
      })
    },
    submit() {
      let self = this
      if(this.fileList.length) {
        self.form.setFieldsValue({
          'lightPic': this.fileList
        })
      } else {
        self.form.setFieldsValue({
          'lightPic': undefined
        })
      }
      // this.$router.push({path: '/articleManage', query: {columnId: self.$route.query.columnId}})
      this.form.validateFields((err, value) => {
        if (!err) {
          self.confirmLoading = true
          let articleLabels = []
          for(let x in self.selectedTags) {
            articleLabels.push({
              id: self.selectedTags[x].id,
              name: self.selectedTags[x].name
            })
          }
          let formData = Object.assign(this.model, value);
          formData.viewpermission = self.permissionSubmit(value.viewpermission)
          formData.downloadpermission = self.permissionSubmit(value.downloadpermission)
          //取消缩略图校验
          if (self.fileList.length>1){
            formData.titleImgUrl = self.fileList[0].url
          }

          let articleAttachmentsArr = []
          for(let y in self.fileList2) {
            articleAttachmentsArr.push({
              filename: self.fileList2[y].name,
              attachment:self.fileList2[y].url
            })
          }
          formData.articleAttachments = articleAttachmentsArr
          formData.articleLabels = articleLabels
          delete formData.uploadPath
          delete formData.lightPic
          let url
          if(self.$route.query.articleId) {
            url = '/article/update'
          } else {
            url = '/article/save'
          }
          postAction(url, formData).then(res => {
            if(res.code == 0) {
              self.$message.success(res.msg)
              self.confirmLoading = false
              self.$router.push({path: '/articleManage', query: {columnId: self.$route.query.columnId}})
            } else {
              self.$message.error(res.msg)
              self.confirmLoading = false
            }
          })
        }
      })
    },
    getTagList() {
      let self = this
      getAction('/articleLabel/getall', {}).then(res => {
        if (res.code == 0) {
          self.tags = [...res.result]
        }
      })
    },
    handleChange(tag, checked) {
      if(checked) {
        this.selectedTags.push(tag)
      } else {
        for(let x in this.selectedTags) {
          if(this.selectedTags[x].id == tag.id) {
            this.selectedTags.splice(x, 1)
          }
        }
      }
    },
    deleteTagAction(tag) {
      let self = this
      let param = {
        id: tag.id
      }
      postAction('/articleLabel/delbyid', param).then(res => {
        if(res.code == 0) {
          self.$message.success(res.msg)
          for(let x in self.selectedTags) {
            if(self.selectedTags[x].id == tag.id) {
              self.selectedTags.splice(x,1)
            }
          }
          self.$nextTick(() => {
            self.getTagList()
          })
        }
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      let self = this
      if(inputValue) {
        let params = {
          name: inputValue
        }
        postAction('/articleLabel/add', params).then(res => {
          if (res.code == 0) {
            self.selectedTags.push(
              {
                id: res.result.id
              }
            )
            self.getTagList()
          }
        })
      }
      self.inputVisible = false
      self.inputValue = ''
    },
    showTag(index) {
      if(index > 10) {
        if(this.toggleSearchStatus) {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    },
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },
    checkedTag(tag) {
      let arr = []
      for(let x = 0; x <this.selectedTags.length; x++) {
        arr.push(this.selectedTags[x].id)
      }
      return arr.indexOf(tag.id) > -1
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },
    imgHandleCancel() {
      this.imgPreviewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.imgPreviewVisible = true;
    },
    goBack() {
      this.$router.push({path: '/articleManage', query: {columnId: this.$route.query.columnId}})
    }
  }
};
</script>

<style lang="less">
  .EditArticle {
    .rowStyle {
      margin-bottom: 20px;
    }
    .modelTitle {
      font-size: 14px;
      font-weight: 700;
    }
    // .avatar-uploader > .ant-upload {
    //   width: 128px;
    //   height: 128px;
    // }
    // .ant-upload-select-picture-card i {
    //   font-size: 32px;
    //   color: #999;
    // }

    // .ant-upload-select-picture-card .ant-upload-text {
    //   margin-top: 8px;
    //   color: #666;
    // }
    .ant-upload.ant-upload-select-picture-card {
      width: 140px;
      height: 140px;
    }
    .ant-upload-list-picture-card .ant-upload-list-item {
      width: 140px;
      height: 140px;
    }
  }
</style>
